<template>
  <div>
    <!--    头部查询区-->
    <el-card style="margin:20px 0;">
      <div style="display: flex">
        <el-input style="width: 35%;margin-right: 20px" placeholder="关键字查询，范围:名称、ip、备注"
                  v-model.trim="queryInfo.query" @clear="queryAreaSelectChange" clearable>
          <el-button id="searchButton" slot="append" icon="el-icon-search" @click="queryAreaSelectChange"></el-button>
        </el-input>
        <div class="areaSelect">
          <el-select
            @click.native="getuArealist()"
            @change="queryAreaSelectChange"
            popper-class="areaSelect"
            v-model="queryInfo.area"
            placeholder="选择网络区域" clearable>
            <el-option v-for="item in arealist" :style="{background:item.yanse}" :key="item._id" :value="item._id"
                       :label="item.name">
            </el-option>
          </el-select>

        </div>
        <el-input style="width: 180px;margin-right: 20px" onkeyup="value=value.replace(/[^\d]/g,'')"
                  v-model="queryInfo.vlan" placeholder="vlan号" @clear="queryAreaSelectChange" clearable>
          <el-button id="searchButton1" slot="append" icon="el-icon-search" @click="queryAreaSelectChange"></el-button>
        </el-input>
        <el-dropdown trigger="click">
          <el-tooltip content="新增IP记录">
            <el-button type="success" icon="el-icon-plus" circle></el-button>
          </el-tooltip>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-link :underline="false" @click="dialogVisible=true">手动添加</el-link>
            </el-dropdown-item>
            <el-dropdown-item>
              <el-link :underline="false" @click="redSnmpDialogVisible=true">SNMP读取</el-link>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-tooltip content="刷新列表" style="margin-left: 5px">
          <el-button icon="el-icon-refresh" circle @click="refresh"></el-button>
        </el-tooltip>
        <el-button @click="drawer=true">IP地址计算工具</el-button>
        <el-button @click="drawerTest=true">测试工具</el-button>
      </div>

    </el-card>
    <!--    IP计算工具区-->
    <el-drawer title="ip地址计算器" :visible.sync="drawer" direction="ttb" size="auto">
      <div style="margin:20px 0;">
        <el-row :gutter="20">
          <el-form :model="iptoolForm" ref="iptoolForm" :rules="iptoolFormRules">
            <el-col :span="8">
              <el-form-item prop="ipaddr">
                <el-input :validate-event="false" v-model="iptoolForm.ipaddr" placeholder="请输入IP地址，仅支持IPV4" clearable>
                  <template slot="prepend" style="width: 80px">IP:</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="yanma">
                <el-input :validate-event="false" v-model="iptoolForm.yanma" placeholder="如：255.255.255.0 或 24"
                          clearable>
                  <template slot="prepend" style="width: 80px">掩码：</template>
                </el-input>
              </el-form-item>

            </el-col>
          </el-form>
          <el-col :span="2" style="display: flex">
            <el-button type="success" @click="jisuanIp">计算</el-button>
            <el-button @click="reset">重置</el-button>
          </el-col>
          <!--        <el-col :span="4">-->
          <!--          <el-dropdown>-->
          <!--            <el-button type="primary">-->
          <!--              计算要求<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
          <!--            </el-button>-->
          <!--            <el-dropdown-menu slot="dropdown">-->
          <!--              <el-dropdown-item @click.native="testip()">验证IP</el-dropdown-item>-->
          <!--              <el-dropdown-item @click="testYanma()">验证掩码</el-dropdown-item>-->
          <!--              <el-dropdown-item @click="yanma2()">掩码转换</el-dropdown-item>-->
          <!--              <el-dropdown-item @click="yanma2()">算出广播地址和网络地址</el-dropdown-item>-->
          <!--              <el-dropdown-item @click="getFanwei">列出IP范围</el-dropdown-item>-->
          <!--            </el-dropdown-menu>-->
          <!--          </el-dropdown>-->
          <!--        </el-col>-->
        </el-row>


        <!--      计算显示区-->
        <div v-if="textarea" style="width: 100%;display: flex;　　justify-content: center;">
          <div style="width: 50%;padding: 30px;">
            <!--        <span v-if="textarea===''" style="color: #909399;font-size: small">计算结果显示区</span>-->
            <div style="text-align: left;border-radius:5px;border: 1px solid;padding-top: 20px">
              <span class="label">IP地址:</span> <span>{{textarea.ip}}</span>
              <el-divider></el-divider>
              <span class="label">子网掩码:</span> <span>{{textarea.yanma.s}}   /   {{textarea.yanma.n}}</span>
              <el-divider></el-divider>
              <span class="label">网络地址:</span> <span>{{textarea.wangluoip}}</span>
              <el-divider></el-divider>
              <span class="label">广播地址:</span> <span>{{textarea.guangboip}}</span>
              <el-divider></el-divider>
              <span class="label">主机数:</span>
              <span>共{{textarea.ips.length}}个IP &nbsp;&nbsp;可用{{textarea.ips.length-2}}个</span>
              <el-divider></el-divider>
              <span class="label">可用IP范围:</span>
              <span>{{textarea.ips[0]}} -- {{textarea.ips[textarea.ips.length-1]}}</span>
              <el-divider></el-divider>
            </div>
          </div>
        </div>

      </div>
    </el-drawer>

    <el-drawer title="网络测试工具" :visible.sync="drawerTest" direction="ttb" size="auto" style="text-align: center">
      <el-row type="flex" justify="center" style="margin-bottom: 20px">
        <el-col :span="12">
          <el-form :model="testForm" :rules="testForm_rules" ref="testForm">
            <el-form-item prop="type" label="测试类型: " label-width="120px">
              <el-select style="width: 100%;" v-model="testForm.type" @change="changeType">
                <el-option label="Ping测试" value="ping"></el-option>
                <el-option label="Traceroute跟踪" value="traceroute"></el-option>
                <el-option label="TCP端口测试" value="tcp"></el-option>
                <el-option label="PING扫描网段" value="netPing"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="testForm.type!=='netPing'" prop="ip" label="ip地址：" label-width="120px">
              <el-input v-model="testForm.ip" placeholder=""></el-input>
            </el-form-item>
            <el-form-item v-else prop="network" label="ip网段：" label-width="120px">
              <el-input v-model="testForm.network" placeholder="格式：192.168.0.1-254,扫描1-254" clearable></el-input>
            </el-form-item>
            <el-form-item v-if="testForm.type=='tcp'" prop="tcp" label="tcp端口：" label-width="120px">
              <el-input oninput="value=value.replace(/[^0-9.]/g,'')" v-model="testForm.tcp"
                        placeholder="默认为80,1到65535"></el-input>
            </el-form-item>
          </el-form>
          <el-row type="flex" justify="center">
            <el-col :span="8">
              <el-button type="success" @click="netTest()">执 行</el-button>
            </el-col>
            <el-col :span="8">
              <el-button @click="resetTest()">重 置</el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <!--      结果显示区-->
      <div v-if="testOutarea" ref="testOutarea"
           style="display: flex;　　justify-content: center;background:#909399;color: white ">
        <div v-if="testloading" style=" width:100%;height: 200px"
             v-loading="testloading"
             element-loading-text="等待测试结果中..."
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)"></div>
        <div v-if="!testloading" style="width: 100%;padding: 30px;display: flex;justify-content: center;">

          <!--          PING结果显示-->
          <div v-if="pingArea"
               style="width: 50%;text-align: left;border-radius:5px;border: 1px solid;padding-top: 20px">
            <span class="label">状态:</span> <span v-if="htmlMsg.status=='online'"><i style="color: green;font-size: 150%"
                                                                                    class="el-icon-success"></i></span><span
            v-else><i style="color: red;font-size: 150%" class="el-icon-error"></i></span>
            <el-divider></el-divider>
            <span class="label">目标IP:</span> <span>{{htmlMsg.host}}</span>
            <el-divider></el-divider>
            <span class="label">平均速度:</span> <span>{{htmlMsg.res_avg}}</span>
            <el-divider></el-divider>
            <span class="label">丢包个数:</span> <span>{{htmlMsg.packet_loss}}</span>
            <el-divider></el-divider>
          </div>
          <!--          TCP结果显示-->
          <div v-if="tcpArea" style="width: 50%;text-align: left;border-radius:5px;border: 1px solid;padding-top: 20px">
            <span class="label">状态:</span> <span v-if="htmlMsg.success"><i style="color: green;font-size: 150%"
                                                                           class="el-icon-success"></i></span><span
            v-else><i style="color: red;font-size: 150%" class="el-icon-error"></i></span>
            <el-divider></el-divider>
            <span class="label">目标IP:</span> <span>{{htmlMsg.host}}</span>
            <el-divider></el-divider>
            <span class="label">目标端口:</span> <span>{{htmlMsg.port}}</span>
            <el-divider></el-divider>
            <span class="label">本次用时:</span> <span>{{htmlMsg.time}}ms</span>
            <el-divider></el-divider>
          </div>
          <!--          网段扫描结果显示-->
          <div v-if="scanArea" style="width:100%;">
            <h5>扫描测试：{{testForm.network}},在线IP共：{{htmlMsg.length}}</h5>
            <el-table
              :data="htmlMsg"
              style="width: 100%;margin-top: 20px"
              :default-sort="{prop: 'ip_address', order: 'descending'}"
            >
              <el-table-column
                prop="ip_address"
                label="IP地址"
                sortable>
              </el-table-column>
              <el-table-column
                prop="packet_loss"
                label="丢包数">
              </el-table-column>
              <el-table-column
                prop="res_avg"
                label="平均速率">
              </el-table-column>
              <el-table-column
                prop="status"
                label="在线状态">
              </el-table-column>
            </el-table>
          </div>
          <!--          路由跟踪结果显示-->
          <div v-if="tracerouteArea" style="width:100%;">
            <el-table :data="traceData">
              <el-table-column
                width="180"
                prop="event"
                label="事件"></el-table-column>
              <el-table-column
                prop="msg"
                label="内容"></el-table-column>
            </el-table>
            <el-button style="margin: 5px" size="small" type="warning" @click="stopSse">停止追踪</el-button>
          </div>
        </div>

      </div>
    </el-drawer>

    <!--    列表显示区-->
    <el-table :data="iplistData" style="width: 100%"
              ref="ipsTable"
              element-loading-text="拼命加载中"
              element-loading-spinner="el-icon-loading"
              v-loading="fullscreenLoading"
              @row-click="ctdk">
      <!--   展开区-->
      <el-table-column type="expand">
        <template slot-scope="props">
          <!--          首行信息区-->
          <el-row v-if="props.row.type === 'IP网段'" type="flex" class="row-bg" justify="center">
            <el-col style="text-align: center">
              <span class="titlelabel">VLAN：</span>{{props.row.vlan}}
              <span class="titlelabel">名称：</span>{{props.row.name}}
              <span class="titlelabel">网关IP：</span>{{props.row.ip}}
              <span class="titlelabel">掩码：</span>{{props.row.yanmaObj.s}} /{{props.row.yanmaObj.n}}
              <span class="titlelabel">主机IP数：</span>{{props.row.ipcountinfo.count}}
              <span class="titlelabel">启始IP：</span>{{props.row.ipcountinfo.startIP}}
              <span class="titlelabel">末尾IP：</span>{{props.row.ipcountinfo.endIP}}
              <span class="titlelabel">snmp设置：</span>
              <span v-if="props.row.snmpInfo">
                <el-link @click="openSnmpInfo(props.row._id,props.row.name,props.row.snmpInfo)">
                {{props.row.snmpInfo.ip}}<i
                  class="el-icon-s-tools el-icon--right"></i></el-link>
                <span class="titlelabel">定时扫描：</span>
                <el-tooltip content="开启/关闭 ARP定时扫描功能" placement="bottom" effect="light">
                  <el-popconfirm title="你确定要更改状态吗？" @confirm="changeTimeSan(props.row)">
                     <el-switch v-model="props.row.snmpInfo.timeSan"
                                :active-value=true
                                :inactive-value=false
                                slot="reference"
                                @change="changeTimeSanFirst(props.row)"></el-switch>
                  </el-popconfirm>

                </el-tooltip>
              </span>

              <span v-else>无</span>
              <span class="titlelabel">备注：</span>{{props.row.beizhu}}
              <el-button size="mini" @click="importIpname(props.row._id,props.row.ips)">导入IP名称</el-button>
            </el-col>
            <!--            <el-col :span="4">-->
            <!--              &lt;!&ndash;修改按钮&ndash;&gt;-->
            <!--              <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">-->
            <!--                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openedit(scope.row)"-->
            <!--                           onClick="event.cancelBubble = true"></el-button>-->
            <!--              </el-tooltip>-->
            <!--              &lt;!&ndash;删除按钮&ndash;&gt;-->
            <!--              <el-tooltip style="margin-left: 5px" effect="dark" content="删除" placement="top" :enterable="false">-->
            <!--                <el-popconfirm title="确定删除吗？" @confirm="deleteDevice(scope.row)">-->
            <!--                  <el-button type="danger" icon="el-icon-delete" slot="reference" size="mini"-->
            <!--                             onClick="event.cancelBubble = true"></el-button>-->
            <!--                </el-popconfirm>-->
            <!--              </el-tooltip>-->

            <!--            </el-col>-->
          </el-row>
          <!--          网段详细IP列表-->
          <el-row>
            <el-col justify="center">
              <!--              u-table实际虚拟加载，不卡！-->
              <u-table :row-height="55"
                       showHeaderOverflow="title"
                       use-virtual height="400"
                       v-if="props.row.type === 'IP网段'"
                       use-virtual
                       :data="props.row.ips.filter(data =>  !searchIP[props.$index] || data.ip.toLowerCase().includes(searchIP[props.$index].toLowerCase()))"
                       ref="uTable"
              >
                <u-table-column align="center" prop="ip" label="IP地址">
                  <!--                  slot-scope="scope"-->
                  <template slot="header" slot-scope="scope">
                    <el-dropdown trigger="click">
                      <span><span :style="{color:searchIP[props.$index]?'#409EFF':'#909399'}">IP地址</span><i
                        class="el-icon-search" style="margin-left: 5px;color: #409EFF"></i></span>
                      <el-dropdown-menu>
                        <el-input placeholder="输入关键字搜索IP" v-model="searchIP[props.$index]"
                                  clearable></el-input>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </u-table-column>
                <u-table-column align="center" label="VLAN">
                  <template slot-scope="scope">{{ props.row.vlan}}</template>
                </u-table-column>
                <u-table-column label="掩码地址">
                  <template slot-scope="scope">{{ props.row.yanmaObj.s}}</template>
                </u-table-column>
                <u-table-column align="center" prop="name" label="名称说明">
                  <template slot-scope="scope">
                    <span v-if="chartIsShow">{{scope.row.name}}</span>
                  </template>
                  <template slot="header" slot-scope="scope">
                    <el-dropdown trigger="click">
                      <span><span :style="{color:searchName[props.$index]?'#409EFF':'#909399'}">名称说明</span><i
                        class="el-icon-search" style="margin-left: 5px;color: #409EFF"></i></span>
                      <el-dropdown-menu>
                        <el-input placeholder="输入关键字搜索" v-model="searchName[props.$index]"
                                  @input="changeSearchName(searchName[props.$index],props)"
                                  clearable></el-input>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </u-table-column>
                <u-table-column align="center" label="MAC地址"
                                :filters="[{ text: '有MAC记录', value: 'has' }, { text: '无MAC记录', value: 'nohas'},{ text: 'MAC变更过', value: 'wanning'},{ text: '1周内未上线', value: 'week'},{ text: '90天内未上线', value: '90day'}]"
                                :filter-method="filterMac">
                  <!--                  设置列下拉筛选并且变色-->
                  <template slot="header" slot-scope="scope">
                    <el-dropdown trigger="click">
                      <span @click.stop="showSearchIP(scope)"><i class="el-icon-search"
                                                                 style="margin-right: 5px;color: #409EFF"></i><span
                        :style="{color:searchMAC[props.$index]|| scope.column.filteredValue.length>0 ?'#409EFF':'#909399'}">MAC地址</span></span>
                      <el-dropdown-menu>
                        <el-input placeholder="输入关键字搜索MAC记录" v-model="searchMAC[props.$index]"
                                  @input="changeSearch(searchMAC[props.$index],props)"
                                  clearable></el-input>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                  <template slot-scope="scope">
                    <span v-if="scope.row.arpstatus=='online'"><i class="el-icon-success"
                                                                  style="color:#67C23A "></i></span>
                    <span v-if="scope.row.arpstatus=='offline'"><i class="el-icon-error"
                                                                   style="color:#F56C6C "></i></span>
                    <el-popover v-if="scope.row.arp" placement="right" trigger="click">
                      <el-descriptions :column="2" border>
                        <el-descriptions-item label="当前MAC：">{{scope.row.arp.mac}}</el-descriptions-item>
                        <el-descriptions-item label="获取时间：">{{new Date(scope.row.arp.time).toLocaleString()}}
                        </el-descriptions-item>
                        <el-descriptions-item v-if="scope.row.oldarp" label="上次MAC：">{{scope.row.oldarp.mac}}
                        </el-descriptions-item>
                        <el-descriptions-item v-if="scope.row.oldarp" label="获取时间：">{{new
                          Date(scope.row.oldarp.time).toLocaleString()}}
                        </el-descriptions-item>
                      </el-descriptions>
                      <el-link slot="reference" :underline="false">{{scope.row.arp.mac}}</el-link>
                    </el-popover>
                    <el-tooltip v-if="scope.row.oldarp" content="MAC发生过变更!" effect="light">
                      <i class="el-icon-warning" style="color: #E6A23C"></i>
                    </el-tooltip>
                    <span v-if="scope.row.arpstatus=='arping'" style="color:#409EFF "><i class="el-icon-loading"></i> 扫描中...</span>
                  </template>
                </u-table-column>
                <u-table-column align="center" prop="use" label="使用情况"
                                :filters="[{ text: '已使用', value: true },{ text: '未使用', value: false }]"
                                :filter-method="filterUse">
                  <template slot-scope="scope">
                    <el-tag size="mini" v-if="scope.row.use" effect="dark">已使用</el-tag>
                    <el-tag size="mini" v-else type="info">未使用</el-tag>
                  </template>
                </u-table-column>
                <u-table-column align="center" label="连接测试"
                                :filters="[{ text: 'PING在线', value: 'success' }, { text: 'PING不通的', value: 'error'}]"
                                :filter-method="filterPING">
                  <template slot-scope="scope">
                    <el-button v-if="!scope.row.ping" size="mini" @click="rowPing(scope.row)">ping</el-button>
                    <span v-if="scope.row.ping=='ping'" style="color:#409EFF "><i
                      class="el-icon-loading"></i> 测试中...</span>
                    <span v-if="scope.row.ping=='success'"><i class="el-icon-success" style="color:#67C23A "></i> 在线
                  <el-tooltip class="item" effect="dark" content="重试" placement="top-start">
                  <el-link :underline="false" @click="rowPing(scope.row)">
                  <i class="el-icon-refresh"></i>
                  </el-link>
                  </el-tooltip>
                </span>
                    <span v-if="scope.row.ping=='error'"><i class="el-icon-error" style="color:#F56C6C "></i> 不通
                  <el-tooltip class="item" effect="dark" content="重试" placement="top-start">
                  <el-link :underline="false" @click="rowPing(scope.row)">
                  <i class="el-icon-refresh"></i>
                  </el-link>
                  </el-tooltip>
                </span>
                  </template>
                </u-table-column>

                <u-table-column align="center" label="操作" style="width: 140px">
                  <template slot-scope="scope">
                    <!--                <span>{{scope.row.name}}</span>-->
                    <el-dropdown>
                      <el-link :underline="false">
                        <i class="el-icon-s-tools"></i><i class="el-icon-arrow-down el-icon--right"></i>
                      </el-link>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="setIpuse(props.row._id,scope.row,true)"><i
                          class="el-icon-circle-check"
                          style="color: green"></i> 标记为已使用
                        </el-dropdown-item>
                        <el-dropdown-item @click.native="setIpuse(props.row._id,scope.row,false)"><i
                          class="el-icon-circle-close"
                          style="color: red"></i> 标记为未使用
                        </el-dropdown-item>
                        <el-dropdown-item @click.native="editIpname(props.row._id,scope.row)"><i class="el-icon-edit"
                                                                                                 style="color: blue"></i>编辑名称
                        </el-dropdown-item>
                        <el-dropdown-item @click.native="openConnect(scope.row)"><i class="el-icon-s-platform"
                                                                                    style="color:green"></i>远程连接
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </u-table-column>
              </u-table>
            </el-col>
          </el-row>

        </template>
      </el-table-column>


      <el-table-column prop="area" label="区域">
        <template slot-scope="scope">
          <el-tag :style="{background:scope.row.area.yanse ,color:'white'}">{{scope.row.area.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="vlan" label="vlan"></el-table-column>
      <el-table-column prop="type" label="类型"></el-table-column>
      <el-table-column prop="name" label="名称">
        <template slot-scope="scope"><span :key="scope.row._id">{{scope.row.name}}</span></template>
      </el-table-column>
      <el-table-column prop="ip" label="ip">
        <template slot-scope="scope">
          <span v-if="scope.row.type ==='IP网段'">网关:</span>{{scope.row.ip}}
        </template>
      </el-table-column>
      <el-table-column prop="yanmaObj.s" label="子网掩码"></el-table-column>
      <el-table-column prop="wangluoip" label="网络号"></el-table-column>
      <el-table-column prop="guangboip" label="广播地址"></el-table-column>
      <el-table-column label="操作" style="width: 80px">
        <template slot-scope="scope">
          <el-dropdown trigger="click">
            <el-link :underline="false" @click.native.stop>
              <i class="el-icon-s-tools"></i><i class="el-icon-arrow-down el-icon--right"></i>
            </el-link>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="deleteIp(scope.row._id)"><i class="el-icon-delete"
                                                                           style="color: red"></i> 删除
              </el-dropdown-item>
              <el-dropdown-item @click.native="editIp(scope.row)"><i class="el-icon-edit" style="color: blue"></i> 修改
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.type === 'IP网段'" @click.native="rowScan(scope.row)">
                <i class="el-icon-search" style="color: #67C23A"> </i>
                <el-tooltip class="item" effect="dark" content="扫描PING此网段,只支持C类段" placement="top-start">
                  <span>PING网段</span>
                </el-tooltip>
              </el-dropdown-item>
              <el-dropdown-item v-if="scope.row.type === 'IP网段'" @click.native="getArpScan(scope.row)">
                <i class="el-icon-search" style="color: #67C23A"> </i>
                <el-tooltip class="item" effect="dark" content="获取网段内在线的IP-MAC关系" placement="top-start">
                  <span>ARP扫描</span>
                </el-tooltip>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!--      分页区域-->
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[20,50,100]"
        :page-size="queryInfo.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!--新建IP弹框-->
    <el-dialog title="新增IP记录" :visible.sync="dialogVisible" @close="addIpFormClose">
      <el-form :model="addIpForm" :rules="addIpFormRules" ref="addIpForm" label-width="100px" style="text-align: left">
        <el-row>
          <el-col :span="8">
            <el-form-item prop="type" label="类型：">
              <el-select filterable v-model="addIpForm.type" @change="typeChange()">
                <el-option value="主机地址" label="主机地址"></el-option>
                <el-option value="IP网段" label="IP网段"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="area" label="网络区域：">
              <el-select class="yanseSelect" @click.native="getuArealist()"
                         v-model="addIpForm.area"
                         ref="template1"
                         @change="colorSelectChangeforid"
                         :popper-append-to-body="false"
                         @visible-change="v => visibleChange(v,'template1',  'ship')">
                <el-option v-for="item in arealist" :style="{background:item.yanse}" :key="item._id" :value="item._id"
                           :label="item.name">
                  <!--                  <span style="float: left" class="span-style">{{ item.name }}</span>-->
                  <!--                  <div class="flag">-->
                  <!--                    <svg-icon icon="edit" iconClass="template_edit_style" @click="dialogVisible1 = true"/>-->
                  <!--                  </div>-->
                </el-option>
                <!--                <el-option @click.native="dialogVisible1 = true" ><i class="el-icon-circle-plus-outline">&nbsp;新建网络区域</i>-->
                <!--                </el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="vlan" label="VLAN号：">
              <el-input onkeyup="value=value.replace(/[^\d]/g,'')" v-model="addIpForm.vlan" placeholder="请输入数字"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="name" label="名称：">
          <el-input v-model.trim="addIpForm.name" clearable></el-input>
        </el-form-item>

        <div v-if="addIpForm.type === '主机地址'">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="ip" label="主机IP：">
                <el-input v-model="addIpForm.ip" placeholder="请输入IP地址，仅支持IPV4" clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="yanma" label="子网掩码：">
                <el-input v-model="addIpForm.yanma" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="beizhu" label="备注信息：">
            <el-input v-model="addIpForm.beizhu"></el-input>
          </el-form-item>
          <el-row type="flex" justify="center" :gutter="20" style="margin:20px 0 40px 0; ">
            <el-col :span="3" style="margin-right: 10px">
              <el-button type="primary" @click="submitAddIp">提 交</el-button>
            </el-col>
            <el-col :span="3" style="margin-left: 10px">
              <el-button type="info" @click="dialogVisible=false">取 消</el-button>
            </el-col>
          </el-row>
          <i class="el-icon-info"></i><span>说明：主机地址指某个需要访问并记录的目标IP，通常指不是本机房管理并规划的IP</span>
        </div>

        <div v-if="addIpForm.type === 'IP网段'">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="ip" label="网关IP：">
                <el-input v-model="addIpForm.ip" placeholder="请输入IP地址，仅支持IPV4" @input="text.enable = true"
                          clearable></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="yanma" label="子网掩码：">
                <el-input v-model="addIpForm.yanma" placeholder="如：255.255.255.0 或 24" @input="text.enable = true"
                          clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item prop="wangluoip" label="网络地址：">
                <el-input v-model="addIpForm.wangluoip" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="guangboip" label="广播地址：">
                <el-input v-model="addIpForm.guangboip" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="ips" label="地址范围：">
            <el-input :disabled="true" :value="textinfo"></el-input>
          </el-form-item>
          <el-form-item prop="beizhu" label="备注信息：">
            <el-input v-model="addIpForm.beizhu"></el-input>
          </el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="4" style="text-align: center">
              <el-button type="success" @click="ipfanweiInfo">网段计算</el-button>
            </el-col>
            <el-col :span="4" style="text-align: center">
              <el-button type="primary" @click="submitAddIp" :disabled="text.enable">提 交</el-button>
            </el-col>
            <el-col :span="4" style="text-align: center">
              <el-button type="info" @click="dialogVisible=false">取 消</el-button>
            </el-col>
          </el-row>

        </div>


      </el-form>

    </el-dialog>

    <!--    读取SNMP设备-IP记录-->
    <el-dialog title="读取SNMP-IP记录" :visible.sync="redSnmpDialogVisible">
      <el-form :model="redSnmpForm" ref="redSnmpForm" :rules="redSnmpFormRules" v-loading="redSnmpFormLoading"
               element-loading-text="连接读取中">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item prop="ip">
              <el-input placeholder="请输入snmp设备IP" v-model="redSnmpForm.ip" clearable>
                <template slot="prepend">设备IP</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="port">
              <el-input onkeyup="value=value.replace(/[^\d]/g,'')" v-model="redSnmpForm.port">
                <template slot="prepend">端口</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col>
            <el-form-item prop="redKey">
              <el-input placeholder="输入读团体字" v-model="redSnmpForm.redKey" clearable>
                <template slot="prepend">团体字</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-button type="success" @click="redSnmpIP">读 取</el-button>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="snmpIpTable" v-if="!redSnmpFormLoading">
        <el-table-column prop="ifname" label="接口名称"></el-table-column>
        <el-table-column prop="ip" label="ip地址"></el-table-column>
        <el-table-column prop="mask" label="子网掩码"></el-table-column>
        <el-table-column width="150" align="center">
          <template slot-scope="scope">
            <el-button v-if="scope.row.ip !='127.0.0.1'" @click="putIPfromSnmp(scope.row,redSnmpForm)" size="small"
                       type="primary">
              导入
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog :title="netSnmpDialogData.netName+'-网段设定SNMP连接信息'" :visible.sync="netSnmpDialogVisible">
      <el-form :model="netSnmpForm" ref="netSnmpForm" :rules="redSnmpFormRules">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item prop="ip">
              <el-input placeholder="请输入snmp设备IP" v-model="netSnmpForm.ip" clearable>
                <template slot="prepend">设备IP</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="port">
              <el-input onkeyup="value=value.replace(/[^\d]/g,'')" v-model="netSnmpForm.port">
                <template slot="prepend">端口</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col>
            <el-form-item prop="redKey">
              <el-input placeholder="输入读团体字" v-model="netSnmpForm.redKey" clearable>
                <template slot="prepend">团体字</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-button type="success" @click="setNetSnmp">提 交</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
    <!--修改IP弹框-->
    <el-dialog title="修改IP记录" :visible.sync="editIpdialogVisible" @closed="editIpdialogClose">
      <el-form :model="editIpForm" :rules="editIpFormRules" ref="editIpForm" label-width="100px"
               style="text-align: left">
        <el-row>
          <el-col :span="8">
            <el-form-item prop="type" label="类型：">
              <el-select filterable v-model="editIpForm.type" @change="typeChange()" disabled>
                <el-option value="主机地址" label="主机地址"></el-option>
                <el-option value="IP网段" label="IP网段"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="area" label="网络区域：">
              <el-select class="yanseSelect"
                         v-model="editIpForm.area"
                         ref="template"
                         :popper-append-to-body="false"
                         @visible-change="v => visibleChange(v,'template',  'ship')">
                <el-option v-for="item in arealist" :style="{background:item.yanse}" :key="item._id" :value="item._id"
                           :label="item.name">
                  <!--                  <span style="float: left" class="span-style">{{ item.name }}</span>-->
                  <!--                  <div class="flag">-->
                  <!--                    <svg-icon icon="edit" iconClass="template_edit_style" @click="dialogVisible1 = true"/>-->
                  <!--                  </div>-->
                </el-option>
                <!--                <el-option @click.native="dialogVisible1 = true" ><i class="el-icon-circle-plus-outline">&nbsp;新建网络区域</i>-->
                <!--                </el-option>-->
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="vlan" label="VLAN号：">
              <el-input onkeyup="value=value.replace(/[^\d]/g,'')" v-model="editIpForm.vlan" placeholder="请输入数字"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item prop="name" label="名称：">
          <el-input v-model.trim="editIpForm.name" clearable></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="editIpForm.type === 'IP网段'" prop="ip" label="网关IP：">
              <el-input v-model="editIpForm.ip" placeholder="请输入IP地址，仅支持IPV4" clearable></el-input>
            </el-form-item>
            <el-form-item v-else="editIpForm.type === '主机地址'" prop="ip" label="主机IP：">
              <el-input v-model="editIpForm.ip" placeholder="请输入IP地址，仅支持IPV4" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="yanmaObj" label="子网掩码：">
              <el-input v-model="editIpForm.yanma" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!--          <div v-if="editIpForm.type === 'IP网段'">-->
        <el-form-item v-if="editIpForm.type === 'IP网段'" prop="ips" label="地址范围：">
          <el-input :disabled="true"
                    :value="'可用IP数：' + this.editIpForm.ipcountinfo.count + ' 范围：' + this.editIpForm.ipcountinfo.startIP + '--' + this.editIpForm.ipcountinfo.endIP"></el-input>
        </el-form-item>

        <el-form-item prop="beizhu" label="备注信息：">
          <el-input v-model="editIpForm.beizhu"></el-input>
        </el-form-item>
        <el-row type="flex" justify="center" :gutter="20" style="margin:20px 0 40px 0; ">
          <el-col :span="3" style="margin-right: 10px">
            <el-button type="primary" @click="submitEditIp">提 交</el-button>
          </el-col>
          <el-col :span="3" style="margin-left: 10px">
            <el-button type="info" @click="editIpdialogVisible=false">取 消</el-button>
          </el-col>
        </el-row>
        <i class="el-icon-info"></i><span>说明：只能修改网关、vlan、备注，网段范围不可修改，网段只能删除。</span>


      </el-form>
    </el-dialog>

    <!--新建网络区域弹框-->
    <el-dialog
      title="新建网络区域"
      :visible.sync="dialogVisible1"
      ref="areadialog"
      width="30%" @open="openAreaDialog">
      <el-form :model="areaForm" :rules="areaFormRules" ref="areaForm" style="text-align: left">
        <el-row :gutter="20" type="flex" justify="space-around">
          <el-col :span="10">
            <el-form-item prop="name">
              <el-input placeholder="区域名称，如：内外、外网" v-model="areaForm.name">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="yanse">
              <el-select class="yanseSelect" ref="colorSelect" v-model="areaForm.yanse" placeholder="选择标记颜色"
                         @change="colorSelectChange" :popper-append-to-body="false">
                <el-option style="background: #409EFF" value='#409EFF' label="默认(蓝色)"></el-option>
                <el-option style="background: #67CF22" value="#67CF22" label="绿色"></el-option>
                <el-option style="background:#F56C6C" value="#F56C6C" label="红色"></el-option>
                <el-option style="background:#E6A23C" value="#E6A23C" label="黄色"></el-option>
                <el-option style="background:#909399" value="#909399" label="灰色"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible1 = false">取 消</el-button>
    <el-button type="primary" @click="submitAddArea">确 定</el-button>
  </span>
    </el-dialog>
    <!-- 远程连接弹框-->
    <el-dialog style="padding:0" :visible.sync="dialogVisibleConnect" @close="closeConnect()">
      <conectForm ref="conectForm" :connIp="connIp"></conectForm>
    </el-dialog>
    <!--    行数据查询抽屉-->
    <el-drawer
      title="标题"
      :visible.sync="viewdrawer"
      :with-header="false"
      size="50%">
      <div style="margin: 20px 10px;">
        <h1 style="margin-bottom: 40px">{{rowForm.name}}</h1>
        <el-row>
          <el-col :span="8" style="text-align: left">
            <span class="label">网络区域:</span>
            <span> <el-tag
              :style="{background:this.rowForm.area.yanse ,color:'white'}">{{rowForm.area.name}}</el-tag></span>
          </el-col>
          <el-col :span="8" style="text-align: left">
            <span class="label">类型:</span>
            <span> {{rowForm.type}}</span>
          </el-col>
          <el-col :span="8" style="text-align: left">
            <span class="label">VLAN号:</span> <span> {{rowForm.vlan}}</span>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row>
          <el-col :span="12" style="text-align: left">
            <div v-if="rowForm.type=='主机地址'"><span class="label">主机地址:</span><span> {{rowForm.ip}}</span></div>
            <div v-if="rowForm.type=='IP网段'"><span class="label">网关地址:</span><span> {{rowForm.ip}}</span></div>
          </el-col>
          <el-col :span="12" style="text-align: left">
            <span class="label">子网掩码:</span> <span> {{rowForm.yanmaObj.s}} / {{rowForm.yanmaObj.n}}</span>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div v-if="rowForm.type=='IP网段'">
          <el-row>
            <el-col :span="12" style="text-align: left">
              <span class="label">主机IP数:</span><span> {{rowForm.ipcountinfo.count}}</span>
            </el-col>
            <el-col :span="12" style="text-align: left">
              <span class="label">容纳IP范围:</span>
              <span>{{rowForm.ipcountinfo.startIP}} -- {{rowForm.ipcountinfo.endIP}}</span>
            </el-col>
          </el-row>
          <el-divider></el-divider>
          <el-row>
            <el-col :span="12" style="text-align: left">
              <span class="label">网络地址:</span><span> {{rowForm.wangluoip}}</span>
            </el-col>
            <el-col :span="12" style="text-align: left">
              <span class="label">广播地址:</span> <span> {{rowForm.guangboip}} / {{rowForm.yanmaObj.n}}</span>
            </el-col>
          </el-row>
          <el-divider></el-divider>
        </div>
        <div style="text-align: left">
          <span class="label">备注信息:</span> <span> {{rowForm.beizhu}}</span>
        </div>
      </div>
    </el-drawer>
    <!--    上传ip对应名称json文件-->
    <el-dialog
      :visible.sync="dialogImport"
      title="导入IP地址对应名称"
      v-if="dialogImport"
      width="30%"
      append-to-body="">
      <div style="text-align: center">
        <el-upload
          :limit="1"
          action=""
          ref="upload"
          accept=".json"
          :file-list="fileList"
          :on-success="onSuccess"
          :on-remove="onRemove"
          :on-exceed="handleExceed"
          :on-preview="handlePreview"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            上传json文件，且只能上传 1 个文件
          </div>
        </el-upload>
      </div>
      <span slot="footer">
        <el-button @click="dialogImport = false" size="mini">取 消</el-button>
        <el-button @click="importConfirm" size="mini" type="primary"
        >确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="dialogPreviewJSON"
      title="JSON文件预览"
      v-if="dialogPreviewJSON"
      width="40%"
      append-to-body
    >
      <sjson :json="jsonData"></sjson>
    </el-dialog>

  </div>
</template>

<script>
  import 'babel-polyfill'
  import {EventSourcePolyfill} from 'event-source-polyfill'
  import conectForm from '~/components/connectForm.vue';
  import sjson from '~/components/sjson.vue';
  // 验证IP的正则
  let ip_reg = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  // 验证子网掩码的正则
  let mask_reg = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(255|254|252|248|240|224|192|128|0)$/;


  let id = 1000;
  export default {
    middleware: 'metaTitle',
    meta: {title: 'IP地址表'},
    name: "iptable",
    components: {conectForm, sjson},
    data() {
      return {
        connIp: '',
        traceData: [],
        evtSource: null,
        pingArea: false,
        scanArea: false,
        tcpArea: false,
        tracerouteArea: false,
        chartIsShow: true,
        testloading: false,
        textinfo: '',
        fullscreenLoading: true,
        text: {enable: true},
        iplistData: [],
        iplistDataBak: [],
        iptoolForm: {ipaddr: '', yanma: '',},
        testForm: {type: 'ping'},
        areaForm: {yanse: '#409EFF'},
        arealist: [],
        rowForm: {area: {yanse: ''}, yanmaObj: {s: '', n: ''}},
        testForm_rules: {
          ip: [{required: true, message: '输入不能为空', trigger: 'blur',}, {pattern: ip_reg, message: 'IP地址格式不正确'}],
          network: [{required: true, message: '输入不能为空', trigger: 'blur',}, {
            validator: this.validNetping,
            trigger: 'blur'
          }],
          tcp: []
        },
        areaFormRules: {
          name: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          yanse: [{required: true, message: '输入不能为空', trigger: 'blur',},],
        },
        iptoolFormRules: {
          ipaddr: [{required: true, message: '输入不能为空', trigger: 'blur',}, {pattern: ip_reg, message: 'IP地址格式不正确'}],
          yanma: [{required: true, message: '输入不能为空', trigger: 'blur'}, {validator: this.testYanma,},],
        },
        addIpFormRules: {
          type: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          area: [{required: true, message: '网络区域不能为空', trigger: 'blur',},],
          name: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          ip: [{required: true, message: '输入不能为空', trigger: 'blur',}, {
            pattern: ip_reg,
            message: 'IP地址格式不正确',
            trigger: 'blur',
          }],
          yanma: [{required: true, message: '输入不能为空', trigger: 'blur'}, {validator: this.testYanma, trigger: 'blur',},],
        },
        editIpFormRules: {
          type: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          area: [{required: true, message: '网络区域不能为空', trigger: 'blur',},],
          name: [{required: true, message: '输入不能为空', trigger: 'blur',},],
          ip: [{required: true, message: '输入不能为空', trigger: 'blur',}, {
            pattern: ip_reg,
            message: 'IP地址格式不正确',
            trigger: 'blur',
          }],
          yanma: [{required: true, message: '输入不能为空', trigger: 'blur'}, {validator: this.testYanma, trigger: 'blur',},],
        },
        addIpForm: {type: '主机地址', yanma: '255.255.255.255',},
        editIpForm: {},
        redSnmpForm: {ip: '', port: 161},
        netSnmpForm: {ip: '', port: 161},
        netSnmpDialogData: {netId: '', netName: ''},
        snmpIpTable: [],
        redSnmpFormRules: {
          ip: [{required: true, message: '请输入设备IP', trigger: 'blur'}, {pattern: ip_reg, message: 'IP地址格式不正确'}],
          port: [{required: true, message: '不能为空', trigger: 'blur'}],
          redKey: [{required: true, message: '不能为空', trigger: 'blur'}]
        },
        dialogVisible: false,
        editIpdialogVisible: false,
        redSnmpDialogVisible: false,
        netSnmpDialogVisible: false,
        dialogVisibleConnect: false,
        redSnmpFormLoading: false,
        dialogVisible1: false,
        textarea: '',
        testOutarea: false,
        htmlMsg: '',
        total: 0,
        queryInfo: {
          page: 1,
          limit: 20,
        },
        drawer: false,
        drawerTest: false,
        viewdrawer: false,
        searchIP: [],
        searchName: [],
        searchMAC: [],
        fileList: [],
        uploadData: [],
        dialogImport: false,
        jsonData: null,
        dialogPreviewJSON: false,
        currenRowIps: [],
        currenRowID: '',
      }
    },
    created() {
      this.fullscreenLoading = true
      this.getiplistData();
    },

    watch: {},
    computed: {},
    methods: {
      importIpname(rowID, rowIps) {
        this.dialogImport = true
        this.currenRowIps = rowIps
        this.currenRowID = rowID
      },
      handlePreview(file) {
        let reader = new FileReader();
        reader.readAsText(file.raw);
        reader.onload = (e) => {
          this.jsonData = JSON.parse(e.target.result);
          this.dialogPreviewJSON = true;
        };
      },
      // 上传文件超出文件数量限制/文件格式不符合要求时
      handleExceed(files, fileList) {
        this.$message.warning(`每次只能导入一个json文件！`);
      },
      // 移除文件
      onRemove(file) {
        this.fileList = [];
      },
      // 文件上传成功
      onSuccess(res, file, fileList) {
        let reader = new FileReader();
        reader.readAsText(file.raw);
        reader.onload = (e) => {
          this.uploadData = [];
          this.uploadData = JSON.parse(e.target.result);

        };
      },
      // 导入确认
      importConfirm() {
        this.$confirm("导入后原数据会被覆盖，确定导入吗?", "温馨提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          if (this.jsonData) {
            // 使用目标数据变量接收上传后的文件数据
            //this.stockData = this.uploadData;
            //console.log(this.jsonData)
            for (var index in this.currenRowIps) {
              //把表中的IP与JSON文件的IP进行比对
              for (var i in this.jsonData)
                if ((this.currenRowIps[index].ip == this.jsonData[i][0]) && this.jsonData[i][1]) {
                  console.log(this.currenRowIps[index].ip, "---", this.jsonData[i][1])
                  this.currenRowIps[index].name = this.jsonData[i][1]
                  this.currenRowIps[index].use = true
                  this.$axios.put('/api/iptable/' + this.currenRowID + '/' + this.currenRowIps[index]._id, this.currenRowIps[index])
                }
            }

          }

          this.dialogImport = false;

          this.$message({
            type: "success",
            message: "导入成功!",
          });
        });
      },
      getQueryList() {
      },
      ctdk(row) {
        this.viewdrawer = true
        this.rowForm = row
        // console.log(row)

      },
      async deleteIp(id) {
        await this.$confirm("确定移除此IP记录吗？", {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).then(async () => {
          try {
            const res = await this.$axios.delete('/api/iptable/' + id);
            if (res.status === 200 && res.data.code === "success") {
              this.$message.success("删除成功")
              this.getiplistData();
            }
          } catch (e) {
            this.$message.error('操作失败')
          }
        }).catch(() => {
          console.log('取消操作');
        })
        // if (isTrue) {
        //
        //
        // }
      },
      editIpdialogClose() {
        this.editIpForm = {};
      },
      async editIp(rowData) {
        if(this.queryInfo.query && this.queryInfo.query.length>0){
          this.$message.warning("当前数据可能包含查询条件，清除关键字后执行修改操作")
          return
        }
        this.editIpdialogVisible = true;
        await this.getuArealist()
        this.editIpForm = JSON.parse(JSON.stringify(rowData))
        this.editIpForm.area = this.editIpForm.area._id
        this.editIpForm.yanma = this.editIpForm.yanmaObj.s


      },
      //修改网段中的某个具体IP的名称
      /*
        rowId ：IP网段记录的ID号
        ipObj：具体ip的完全对像
       * */
      editIpname(rowId, ipObj) {
        this.$prompt(`请输入${ipObj.ip} 对应的名称备注`, '提示', {
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          inputValue: ipObj.name
        }).then(async ({value}) => {
          ipObj.name = value
          const res = await this.$axios.put('/api/iptable/' + rowId + '/' + ipObj._id, ipObj)
          //console.log(res)
          if (res.status === 200 && res.data.code === "success") {
            this.$message.success("提交成功")
            this.chartIsShow = false
            this.$nextTick(() => {
              this.chartIsShow = true
            })
          }

        })
      },
      //打开远程连接对话框
      openConnect(ipObj) {
        this.connIp = ipObj.ip
        this.dialogVisibleConnect = true
      },
      closeConnect() {
        this.connIp = ''
      },
      //行记录ping测试
      async rowPing(row) {
        row['ping'] = 'ping'
        this.chartIsShow = false
        this.$nextTick(() => {
          this.chartIsShow = true
        })
        const res = await this.$axios.post('/api/pings', {type: 'ping', ip: row.ip})
        if (res.status === 200) {
          if (res.data.status == 'online') {
            row['ping'] = 'success'
          } else {
            row['ping'] = 'error'
          }
          this.chartIsShow = false
          this.$nextTick(() => {
            this.chartIsShow = true
          })
        }

      },
      //列表中网段扫描
      async rowScan(row) {
        //展开行
        this.$refs.ipsTable.toggleRowExpansion(row, true)

        for (var index in row.ips) {
          row.ips[index]['ping'] = 'ping'
        }
        this.chartIsShow = false
        this.$nextTick(() => {
          this.chartIsShow = true
        })
        const res = await this.$axios.post('/api/pings', {
          type: 'netPing',
          network: `${row.ipcountinfo.startIP}-${row.ipcountinfo.endIP.split('.')[3]}`
        })
        if (res.status === 200) {
          for (var index in row.ips) {
            for (var j in res.data) {
              if (res.data[j]['host'] == row.ips[index]['ip']) row.ips[index]['ping'] = 'success';
              continue;
            }
            if (row.ips[index]['ping'] != 'success') row.ips[index]['ping'] = 'error'
          }
          this.chartIsShow = false
          this.$nextTick(() => {
            this.chartIsShow = true
          })
        }
      },
      async setIpuse(rowId, ipObj, isUse) {
        ipObj.use = isUse
        const res = await this.$axios.put('/api/iptable/' + rowId + '/' + ipObj._id, ipObj)
        //console.log(res)
        if (res.status === 200 && res.data.code === "success") {
          this.$message.success("提交成功")
          this.chartIsShow = false
          this.$nextTick(() => {
            this.chartIsShow = true
          })
        }
      },

      async getiplistData() {
        try {
          const {data: res} = await this.$axios.get('/api/iptable', {params: this.queryInfo}).catch(error => {
            this.$message.error(error)
          });

          if (res.code === "success") {
            this.total = res.result.total
            this.iplistData = res.result.docs
            this.iplistDataBak = JSON.parse(JSON.stringify(this.iplistData))
            this.fullscreenLoading = false
          }
        } catch (e) {
          //console.log(e) nuxt服务器执行时会报错
        }
      },
      ipfanweiInfo() {
        this.$refs.addIpForm.validateField("ip", Error => {
          if (!Error) {
            this.$refs.addIpForm.validateField("yanma", Error2 => {
              if (!Error2) {
                if (this.addIpForm.yanma === '31' || this.addIpForm.yanma === '32' || this.addIpForm.yanma === "255.255.255.255" || this.addIpForm.yanma === "255.255.255.254") return this.$message.error('网段掩码不能大于30位主机掩码')
                this.text = {}
                this.text.ip = this.addIpForm.ip
                //2.得到两种形式的掩码
                this.text.yanma = this.yanma2yanma(this.addIpForm.yanma)
                this.addIpForm.yanmaObj = this.yanma2yanma(this.addIpForm.yanma)
                //3.得到网络IP和广播IP
                this.text.wangluoip = this.get_network_broadcast_addr(this.text.yanma.s, this.text.ip)[0]
                this.addIpForm.wangluoip = this.get_network_broadcast_addr(this.text.yanma.s, this.text.ip)[0]
                this.text.guangboip = this.get_network_broadcast_addr(this.text.yanma.s, this.text.ip)[1]
                this.addIpForm.guangboip = this.get_network_broadcast_addr(this.text.yanma.s, this.text.ip)[1]
                this.addIpForm.ips = this.return_ip(this.text.wangluoip, this.text.guangboip, this.text.ip)
                this.addIpForm.ipcountinfo = {
                  count: this.addIpForm.ips.length,
                  startIP: this.addIpForm.ips[0],
                  endIP: this.addIpForm.ips[this.addIpForm.ips.length - 1]
                }
                this.textinfo = '可用IP数：' + this.addIpForm.ipcountinfo.count + ' 范围：' + this.addIpForm.ipcountinfo.startIP + '--' + this.addIpForm.ipcountinfo.endIP
                if (this.addIpForm.ips.includes(this.addIpForm.ip)) {
                  //使用提交按键可用
                  this.text.enable = false
                } else {
                  this.text.enable = true
                  this.$message.error("网关IP不在可用主机范围内!请核实")
                }

                // return this.text
              }
            });
          }
        });

      },

      async netTest() {
        let _this = this
        switch (this.testForm.type) {
          case "ping":
            this.$refs.testForm.validateField(['ip'], Error => {
              if (!Error) toTest()
            });
            break;
          case "traceroute":
            this.$refs.testForm.validateField(['ip'], Error => {
              if (!Error) toTraceroute()
            });
            break;
          case "tcp":
            this.$refs.testForm.validateField(['tcp', 'ip'], Error => {
              if (!Error) toTest()
            });
            break;
          case "netPing":
            this.$refs.testForm.validateField(['network',], Error => {
              if (!Error) toTest()
            });
            break;
        }

        async function toTest() {
          _this.htmlMsg = ''
          _this.testOutarea = true
          _this.testloading = true
          try {
            const res = await _this.$axios.post('/api/pings', _this.testForm)
            if (res.status === 200) {
              console.log("aaaaaaaaaaaaaaaaaa")
              //let json = JSON.parse(res.data)
              _this.htmlMsg = res.data
              if (_this.testForm.type == "ping") {
                _this.pingArea = true
              }
              if (_this.testForm.type == "tcp") {
                _this.tcpArea = true
              }
              if (_this.testForm.type == "netPing") {
                _this.scanArea = true
              }
            }
            _this.testloading = false
            console.log(_this.testloading)
          } catch (e) {
            console.log(e)
          }
        };

        function toTraceroute() {
          let token = ''
          if (_this.$store.state.user.token) {
            //console.log("请求头加上token")
            token = 'Bearer ' + _this.$store.state.user.token;
          }
          var curPath = window.document.location.host;
          let url = "https://" + curPath + ":443/api/pings?ip=" + _this.testForm.ip
          _this.evtSource = new EventSourcePolyfill(url, {
            headers: {Authorization: token}
          });
          _this.testOutarea = true
          _this.tracerouteArea = true
          _this.traceData = []
          // console.log(this.evtSource)
          _this.evtSource.onopen = function (event) {
            // _this.traceData.push({'event': '成功连接', 'msg': event})
            // console.log('成功连接', event)
          };
          _this.evtSource.addEventListener('open', function (e) {
            //console.log('打开连接', e)
            _this.traceData.push({'event': '开始成功', 'msg': '与服务器连接成功！'})
          })
          _this.evtSource.addEventListener('message', e => {
            var reg = new RegExp("\"", "g");
            let data = e.data.replace(reg, '')
            data = data.replace(/\\/g, '')
            if (data == "close: end") {
              _this.traceData.push({'event': '返回消息', 'msg': '追踪已结束'})
              _this.stopSse()
            } else {
              _this.traceData.push({'event': '返回消息', 'msg': data})
            }
          });
          _this.evtSource.addEventListener('error', event => {
            // if (this.evtSource.readyState == EventSource.CLOSED) {
            //console.log('event was closed');
            _this.traceData.push({'event': '发生错误', 'msg': JSON.stringify(event)})
            _this.evtSource.close();
            // };
          });
          _this.evtSource.addEventListener('close', event => {
            ;
            console.log('close');
            _this.traceData.push({'event': '关闭连接', 'msg': JSON.stringify(event)})
            //_this.evtSource.close();
          });
        };
      },
      //关闭SSE流,会发一个close消息到服务器
      stopSse() {
        this.evtSource.close();
        this.traceData.push({'event': '已断开连接', 'msg': '已断开与服务器的连接'})
        console.log('Connection closed');
      },

      submitEditIp() {
        this.$refs.editIpForm.validate(async valid => {
          let inIps = false
          //检查提交的网关IP
          if (this.editIpForm.type == 'IP网段') {
            for (let item in this.editIpForm.ips) {
              if (this.editIpForm.ips[item].ip === this.editIpForm.ip) inIps = true;
            }
            if (!inIps) return this.$message.error("网关IP不在可用主机范围内!请核实")
          }

          let data = {
            area: this.editIpForm.area,
            name: this.editIpForm.name,
            ip: this.editIpForm.ip,
            vlan: this.editIpForm.vlan,
            beizhu: this.editIpForm.beizhu,
          }
          try {
            const res = await this.$axios.put('/api/iptable/' + this.editIpForm._id, data)
            if (res.status === 200 && res.data.code === "ValidationError") {
              this.$message.error("名称重复")
            }
            if (res.status === 200 && res.data.code === "success") {

              this.$message.success("提交成功")
              this.editIpdialogVisible = false
              this.getiplistData();
            }
          } catch (e) {
            this.$message.error('提交失败')
            console.log(e)
          }

        })

      },
      append(data, node) {
        //console.log(node)
        const newChild = {id: id++, label: 'testtest', children: []};
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },

      remove(node, data) {
        //console.log(node)
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },
      refresh() {
        this.fullscreenLoading = true;
        setTimeout(async () => {
          await this.getiplistData();
          this.fullscreenLoading = false;
          // async ()=>{
          //   await this.getdeviceList();
          //   this.fullscreenLoading = false;
          // }
        }, 300);
      },

      reset() {
        this.$refs.iptoolForm.resetFields()
        this.textarea = ''
      },
      resetTest() {
        this.$refs.testForm.resetFields();
        this.testOutarea = false
      },

      //触发查询网络区域
      async queryAreaSelectChange(value) {
        const {data: res} = await this.$axios.get('/api/iptable', {params: this.queryInfo}).catch(error => {
          this.$message.error(error)
        });
        //console.log(res.result.docs)
        if (res.code === "success") {
          this.iplistData = res.result.docs
          //关键字查询时还要展下每行下的具体IP记录
          if (this.queryInfo.query && (this.queryInfo.query.replace(/(^s*)|(s*$)/g, "").length > 0)) {
            // for (var row in this.iplistData) {
            //   //展开行
            //   this.$refs.ipsTable.toggleRowExpansion(this.iplistData[row], true)
            // }
            var _this = this
            this.iplistData.forEach((row) => {
              if(row.type == "主机类型") return;
              let list = [];
              row.ips.forEach(ip=>{
               // console.log(ip)
                if(ip.ip.includes(this.queryInfo.query)|| (ip.name && ip.name.includes(this.queryInfo.query))){
                  list.push(ip)
                }
              })
              row.ips = list
              this.$nextTick(function () {
                this.$refs.ipsTable.toggleRowExpansion(row, true)
              })

            })

          }
        }

      },
//设置颜色选择框中颜色
      setSelectColor(color, ref) {
        //通过操作dom节点改变样式
        this.$nextTick(() => {
          //let dom = this.$refs.colorSelect;
          let dom = this.$refs[ref];
          if (dom) {
            dom = dom.$el.children[0];
            let inputDom = dom.querySelectorAll(".el-input__inner");
            let icon = dom.querySelectorAll(".el-input__icon");
            inputDom[0].style["background-color"] = color;
            icon[0].style["color"] = "black";
          }
        })
      },
      findOranges(fruit) {
        return fruit._id === 'orange';
      },
      colorSelectChange(val) {

        this.setSelectColor(val, 'colorSelect');
        //触发update事件更新父组件绑定值
        this.$emit('update', val);
      },
      colorSelectChangeforid(val) {
        let item = this.arealist.find(item => item._id === val)
        this.setSelectColor(item.yanse, 'template1');
        //触发update事件更新父组件绑定值
        this.$emit('update', item.yanse);
      },
      openAreaDialog() {
        this.areaForm = {yanse: '#409EFF'};
        this.setSelectColor(this.areaForm.yanse);
      },
      typeChange() {
        if (this.addIpForm.type === "主机地址") {
          //清除一些信息
          this.addIpForm.ipcountinfo = null
          this.addIpForm.guangboip = null
          this.addIpForm.wangluoip = null
          this.addIpForm.yanma = "255.255.255.255"
          this.textinfo = null
          this.text.enable = true
        }
        if (this.addIpForm.type === "IP网段") {
          this.addIpForm.yanma = "255.255.255.0"
        }
      },
      async getuArealist() {
        const res = await this.$axios.get('/api/iparea').catch(eror => {
          this.$message.error(eror)
        })
        if (res.status === 200 && res.data.code === 'success') {
          this.arealist = res.data.result
        }
      },
      //提交新增IP或网段地址
      submitAddIp() {
        this.$refs.addIpForm.validate(
          async valid => {
            if (valid) {
              //显示进度条
              const loading = this.$loading({
                lock: true,
                text: '提交中',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              });
              this.addIpForm.yanmaObj = this.yanma2yanma(this.addIpForm.yanma)
              try {
                if (this.addIpForm.type === "IP网段") {
                  //2.整理IPS列表
                  for (let index in this.addIpForm.ips) {
                    //如果是网关标记一下
                    if (this.addIpForm.ips[index] === this.addIpForm.ip) {
                      this.addIpForm.ips[index] = {ip: this.addIpForm.ips[index], name: '网关', use: true}
                    } else {
                      this.addIpForm.ips[index] = {ip: this.addIpForm.ips[index]}
                    }
                  }

                  //3.查询网段和已经记录的网段是否存在冲突
                }
                //4.提交信息
                const res = await this.$axios.post('/api/iptable', this.addIpForm)
                if (res.status === 200 && res.data.code === "ValidationError") {
                  if (res.data.message.indexOf("wangluoip") != -1) this.$message.error("与已有记录网段存在重叠情况！请检查")
                  else this.$message.error("名称重复")
                }
                if (res.status === 200 && res.data.code === "success") {
                  this.$message.success("提交成功")
                  this.dialogVisible = false
                }
                loading.close()
                this.getiplistData();
              } catch (e) {
                loading.close()
                this.$message.error('提交失败')
                console.log(e)
              }
            }

          }
        )
      },
      addIpFormClose() {
        this.addIpForm = {type: '主机地址', yanma: '255.255.255.255',}
        this.text.enable = true
        this.textinfo = ''
      },

      //提交网络区域标签
      submitAddArea() {
        this.$refs.areaForm.validate(
          async valid => {
            if (valid) {
              const res = await this.$axios.post('/api/iparea', this.areaForm)
              if (res.status === 200 && res.data.code === "ValidationError") {
                this.$message.error("名称重复")
              }
              if (res.status === 200 && res.data.code === "success") {
                this.$message.success("提交成功")
                this.dialogVisible1 = false
              }
            }
          }
        )
      },
      jisuanIp() {
        this.$refs.iptoolForm.validate(
          //1.验证输入内容
          valid => {
            let text = {}
            if (valid) {
              text.ip = this.iptoolForm.ipaddr
              //2.得到两种形式的掩码
              text.yanma = this.yanma2yanma(this.iptoolForm.yanma)
              //3.得到网络IP和广播IP
              text.wangluoip = this.get_network_broadcast_addr(text.yanma.s, this.iptoolForm.ipaddr)[0]
              text.guangboip = this.get_network_broadcast_addr(text.yanma.s, this.iptoolForm.ipaddr)[1]
              text.ips = this.return_ip(text.wangluoip, text.guangboip, this.iptoolForm.ipaddr)
              this.textarea = text
            }
          }
        )
      },
      testip() {
        this.$refs.iptoolForm.validateField("ipaddr",
          Error => {
            if (!Error) {
              if (ip_reg.test(this.iptoolForm.ipaddr)) {
                this.$message("是个IP")
              } else {
                this.$message("不是个IP")
              }
              return ip_reg.test(this.iptoolForm.ipaddr)
            }
          }
        )

      },
      testYanma(rule, value, callback) {
        if (value != null && value != "") {
          //检查是否是数字形式
          if (value >= 0 && value <= 32) return callback()
          if (mask_reg.test(value)) return callback()
          callback(new Error('您输入的掩码格式不正确!'))
        }


        // if (this.yanma >= 0 && this.yanma <= 32) {
        //   return true;
        // }
        // if (mask_reg.test(this.yanma)) return true;
        // this.$message.error("掩码格式错误")
        // return false;
      },
      validNetping(rule, value, callback) {
        if (value.includes('-') === false) callback(new Error('格式错误：应如(192.168.1.1-254)'))
        var network = value.split('-')[0];
        if (!ip_reg.test(network)) callback(new Error('格式错误：-前IP地址格式错误'))
        var ip = value.split('-')[1];
        if (ip > 254) callback(new Error('ip范围是1-254'))
        return callback()
      },
      yanma2yanma(value) {
        let yanma = {n: null, s: ''}
        if (value >= 0 && value <= 32) {
          yanma.n = value
          yanma.s = this.CDIR2netmask(value)
        }
        if (mask_reg.test(value)) {
          yanma.s = value
          yanma.n = this.netmask2CIDR(value)
        }
        return yanma
      },
      //获取网络地址和广播IP
      getWlgb() {
        //1.要验证IP和掩码
        //2.掩码进行转码成255.255.255.0形式
        this.textarea = this.get_network_broadcast_addr(this.yanma, this.ipaddr)
      },

      /***　　把IP地址转换成二进制格式*　　@param string  ip  待转换的IP的地址*/
      ip_to_binary(ip) {
        if (ip_reg.test(ip)) {
          var ip_str = "",
            ip_arr = ip.split(".");

          for (var i = 0; i < 4; i++) {
            let curr_num = ip_arr[i];
            let number_bin = parseInt(curr_num);
            number_bin = number_bin.toString(2);
            let count = 8 - number_bin.length;
            for (var j = 0; j < count; j++) {
              number_bin = "0" + number_bin;
            }
            ip_str += number_bin;
          }
          return ip_str;
        }

        return '';
      },

      /***　　把二进制格式转换成IP地址*　　@param string  binary  待转换的二进制　　*/
      binary_to_ip(binary) {
        if (binary.length == 32) {
          let a = parseInt(binary.substr(0, 8), 2);
          let b = parseInt(binary.substr(8, 8), 2);
          let c = parseInt(binary.substr(16, 8), 2);
          let d = parseInt(binary.slice(-8), 2);
          return a + '.' + b + '.' + c + '.' + d;
        }
        return '';
      },


      /***　　根据子网掩码和网关计算网络地址和广播地址*　　@param string  mask  子网掩码*　　@param string  gateway 网关*/
      get_network_broadcast_addr(mask, ip) {
        let network_broadcast = [];
        let network_addr = "";

        let mask_arr = mask.split(".");
        let ip_arr = ip.split(".");

        // 计算IP的网络地址 与(&)运算
        for (var i = 0; i < 4; i++) {
          let number1 = parseInt(mask_arr[i]);
          let number2 = parseInt(ip_arr[i]);
          network_addr += number1 & number2;
          if (i < 3) {
            network_addr += ".";
          }
        }
        network_broadcast.push(network_addr);

        // 计算广播地址
        // 子掩码后面有几个0，就去掉IP地址后几位再补1
        let mask_binary = this.ip_to_binary(mask);
        let gateway_binary = this.ip_to_binary(ip);

        let mask_zero = mask_binary.split(0).length - 1;
        let one_number = new Array(mask_zero + 1).join('1'); // IP地址后位补1
        let gateway_hou_wei_bu_yi = gateway_binary.slice(0, -mask_zero) + one_number;

        network_broadcast.push(this.binary_to_ip(gateway_hou_wei_bu_yi));

        return network_broadcast;
      },

// 全排列组合算法（两两递归组合）
      doExchange(doubleArrays) {
        var len = doubleArrays.length;
        if (len >= 2) {
          var len1 = doubleArrays[0].length;
          var len2 = doubleArrays[1].length;
          var newlen = len1 * len2;
          var temp = new Array(newlen);
          var index = 0;
          for (var i = 0; i < len1; i++) {
            for (var j = 0; j < len2; j++) {
              temp[index] = doubleArrays[0][i] + '.' + doubleArrays[1][j];
              index++;
            }
          }

          var newArray = new Array(len - 1);
          for (var i = 2; i < len; i++) {
            newArray[i - 1] = doubleArrays[i];
          }
          newArray[0] = temp;

          return this.doExchange(newArray);

        } else {
          return doubleArrays[0];
        }
      },

      /***　　获取由网络地址和广播址组成的所有IP组合*　　@param string  network_addr  网络地址*　　@param string  broadcast_addr 广播地址*　　@param string  gateway     网关*/
      return_ip(network_addr, broadcast_addr, gateway) {
        let range = [];
        let start = network_addr.split(".");
        let end = broadcast_addr.split(".");

        // range格式为[[192], [168], [0,1,2...254], [0,1,2...254]]
        for (var i = 0; i < 4; i++) {
          if (start[i] == end[i]) {
            range[i] = [start[i]];
          } else {
            let min = Math.min(start[i], end[i]);
            let max = Math.max(start[i], end[i]);
            let temp = [];
            // if (i == 3) min = 199; // 从200起计
            for (var j = min; j <= max; j++) {
              temp.push(j);
            }
            range[i] = temp;
          }
        }

        let ip_list = this.doExchange(range);
        ip_list.shift(); // 去掉网络地址
        ip_list.pop(); // 去掉广播地址
        //let gateway_index = -1;

        // 去掉网关
        // for (var k = 0; k < ip_list.length; k++) {
        //   if (ip_list[k] == gateway) {
        //     gateway_index = k;
        //     break;
        //   }
        // }
        // if (gateway_index > -1) {
        //   ip_list.splice(gateway_index, 1);
        // }

        return ip_list;
      },
      // 子网掩码转换 255.255.255.0/24
// 255.255.255.0 转 24
      netmask2CIDR(netmask) {
        return (netmask.split('.').map(Number).map(part => (part >>> 0).toString(2)).join('')).split('1').length - 1;
      },

// 24 转 255.255.255.0
      CDIR2netmask(bitCount) {
        var mask = [];
        for (var i = 0; i < 4; i++) {
          var n = Math.min(bitCount, 8);
          mask.push(256 - Math.pow(2, 8 - n));
          bitCount -= n;
        }
        return mask.join('.');
      },
      /**
       * 为element-ui的Select和Cascader添加弹层底部操作按钮
       * @param visible
       * @param refName  设定的ref名称
       * @param onClick  底部操作按钮点击监听
       * @param addname  底部按钮名称
       */
      visibleChange1(visible, refName, onClick, addname) {
        if (visible) {
          const ref = this.$refs[refName]
          let popper = ref.$refs.popper
          if (popper.$el) popper = popper.$el
          if (!Array.from(popper.children).some(v => v.className === 'el-cascader-menu__list')) {
            const el = document.createElement('ul')
            el.className = 'el-cascader-menu__list'
            el.style = 'border-top: solid 1px #E4E7ED; padding:0; color: #606266;'
            el.innerHTML = `<li class="el-cascader-node text-center" style="height:50px;line-height: 50px">
                <span class="el-cascader-node__label"><i class="font-blue el-icon-plus"></i>` + addname + `</span>
                </li>`
            popper.appendChild(el)
            el.onclick = () => {
// 底部按钮的点击事件 点击后想触发的逻辑也可以直接写在这
              onClick && onClick()
// 以下代码实现点击后弹层隐藏 不需要可以删掉
              if (ref.toggleDropDownVisible) {
                ref.toggleDropDownVisible(false)
              } else {
                ref.visible = false
              }
            }
          }


        }
      },

      visibleChange(visible, refName, type) {
        if (visible) {
          const ref = this.$refs[refName]
          let popper = ref.$refs.popper
          if (popper.$el) popper = popper.$el
          if (!Array.from(popper.children).some(v => v.className === 'el-template-menu__list')) {
            const el = document.createElement('ul')
            el.className = 'el-template-menu__list'
            el.style = 'border-top:2px solid rgb(219 225 241); padding:0; color:rgb(64 158 255);font-size: 13px'
            el.innerHTML = `<li class="el-cascader-node text-center" style="height:37px;line-height: 50px">
                <span class="el-cascader-node__label"><i class="font-blue el-icon-plus"></i> 新建网络区域</span>
                </li>`
            popper.appendChild(el)
            el.onclick = () => {
              if (type === "Ship") {
                // this.showShipTemplate(null, false)
              } else {
                this.dialogVisible1 = true
                // this.showReturnTemplate(null, false)
              }
              if (ref.toggleDropDownVisible) {
                ref.toggleDropDownVisible(false)
              } else {
                ref.visible = false
              }
            }
          }
        }
      },
      // 监听pagesize改变事件
      handleSizeChange(newSize) {
        // console.log(`每页 ${newSize} 条`)
        this.queryInfo.limit = newSize
        this.getiplistData()
      },
      // // 监听页码改变
      handleCurrentChange(newPage) {
        // console.log(`当前页: ${newPage}`)
        this.queryInfo.page = newPage
        this.getiplistData()
      },
      changeType(value) {
        this.testOutarea = false
        this.pingArea = false
        this.tcpArea = false
        this.scanArea = false
        this.tracerouteArea = false
      },
      //获取snmp设备ip
      redSnmpIP() {
        this.$refs.redSnmpForm.validate(async valide => {
          if (valide) {
            this.redSnmpFormLoading = true
            //const res = await this.$axios.get('/api/snmp/redIpaddrs',{params: this.redSnmpForm})
            const res = await this.$axios.get('/api/snmp/redIpaddrs', {params: this.redSnmpForm})
            if (res.status == 200 && res.data.result.success) {
              this.snmpIpTable = res.data.result.data
            } else {
              this.$message.error("读取失败")
            }
            this.redSnmpFormLoading = false
            //console.log(res)
          }

        })

      },
      openSnmpInfo(rowid, rowname, snmpInfo) {
        this.netSnmpDialogData.netId = rowid
        this.netSnmpDialogData.netName = rowname
        this.netSnmpForm = snmpInfo
        this.netSnmpDialogVisible = true
      },
      //获取ARP信息
      async getArpScan(row) {
        const _this = this

        function setStatus(staus) {
          //设置ing显示
          for (var index in row.ips) {
            row.ips[index]['arpstatus'] = staus
          }
          _this.chartIsShow = false
          _this.$nextTick(() => {
            _this.chartIsShow = true
          })
        }

        //if(!(row.snmpInfo.ip && row.snmpInfo.port && row.snmpInfo.redKey)) return this.$message.error("请先设定SNMP连接信息")
        if (!row.hasOwnProperty('snmpInfo')) {
          this.$message.info("请先设定SNMP连接信息")
          this.netSnmpDialogData.netId = row._id
          this.netSnmpDialogData.netName = row.name
          this.netSnmpDialogVisible = true
          return
        }
        try {
          //展开行
          this.$refs.ipsTable.toggleRowExpansion(row, true)
          //设置ing显示
          setStatus('arping')
          // for (var index in row.ips) {
          //   row.ips[index]['arpstatus'] = 'arping'
          // }
          // this.chartIsShow = false
          // this.$nextTick(() => {
          //   this.chartIsShow = true
          // })
          //api获取arp
          const res = await this.$axios.post('/api/snmp/redNetArp', {params: row.snmpInfo, body: row})
          if (res.status == 200 && res.data.code === "success") {
            // if (res.data.result.length > 0) {
            //
            // }
            for (var index in row.ips) {
              for (var j in res.data.result) {
                //对行数据设置成功状态
                if (res.data.result[j]['ip'] == row.ips[index]['ip']) {
                  row.ips[index]['arpstatus'] = 'online'
                  if (row.ips[index].hasOwnProperty('arp') && (res.data.result[j]['mac'] != row.ips[index]['arp']['mac'])) {
                    row.ips[index]['oldarp'] = row.ips[index]['arp']
                  }
                  row.ips[index]['arp'] = {'mac': res.data.result[j]['mac'], 'time': res.data.result[j]['time']}
                }

                continue;
              }
              //对行数据设置失败状态
              if (row.ips[index]['arpstatus'] != 'online') row.ips[index]['arpstatus'] = 'offline'
            }
            this.chartIsShow = false
            this.$nextTick(() => {
              this.chartIsShow = true
            })
          } else {
            this.$message.error('服务器获取失败')
            setStatus('offline')
          }

        } catch (e) {
          this.$message.error('获取失败')
          console.log(e)
        }

      },
      setNetSnmp() {
        this.$refs.netSnmpForm.validate(async valide => {
          try {
            const res = await this.$axios.put('/api/iptable/' + this.netSnmpDialogData.netId, {'snmpInfo': this.netSnmpForm})
            if (res.status === 200 && res.data.code === "ValidationError") {
              this.$message.error("名称重复")
            }
            if (res.status === 200 && res.data.code === "success") {
              this.$message.success("提交成功")
              this.netSnmpDialogVisible = false
              this.getiplistData();
            }
          } catch (e) {
            this.$message.error('提交失败')
            console.log(e)
          }
        })

      },
      //行数据导入IP记录
      putIPfromSnmp(row, snmpForm) {
        //判断掩码是主机还是网段
        if (row.mask == "255.255.255.255") {
          this.addIpForm.type = "主机地址"
        } else {
          this.addIpForm.type = "IP网段"
        }
        this.addIpForm.ip = row.ip
        this.addIpForm.vlan = row.ifname.replace(/[^\d]/g, ' ');
        this.addIpForm.yanma = row.mask
        this.addIpForm.snmpInfo = snmpForm //加入snmp连接信息
        this.dialogVisible = true

      },
      //根据MAC列条件筛选
      filterMac(value, row, column) {
        if (value == 'has') return row.hasOwnProperty('arp')
        if (value == 'nohas') return !row.hasOwnProperty('arp')
        if (value == 'wanning') return row.hasOwnProperty('oldarp')
        if (value == 'week') {
          var bj = 1000 * 3600 * 24 * 7
          //当前时间已经过去一周
          if (row.hasOwnProperty('arp')) return new Date().getTime() - new Date(row.arp.time).getTime() > bj
          else return true
        }
        if (value == '90day') {
          var bj = 1000 * 3600 * 24 * 90
          //当前时间已经过去一周
          if (row.hasOwnProperty('arp')) return new Date().getTime() - new Date(row.arp.time).getTime() > bj
          else return true
        }
        if (value == 'search') return row.hasOwnProperty('arp') && row.arp.mac.toLowerCase().includes()
      },
      filterUse(value, row, column) {
        return row.use == value
      },
      filterPING(value, row, column) {
        if (value == 'success') return row.ping == 'success'
        if (value == 'error') return row.ping == 'error'
        return true
      },
      // clearFilter(props) {
      //   // console.log(props)
      //   // console.log(this.$refs.uTable)
      //   this.$refs.uTable.clearFilter();
      //   //props.$refs.uTable.clearFilter()
      // },
      showSearchIP(props) {
        //console.log(props)
        // // if(!row.seachIP) row.seachIP = ''
        // this.chartIsShow = false
        //  this.$nextTick(() => {
        //    this.chartIsShow = true
        //  })
        // this.$nextTick(_ => {
        //   // this.$refs.seachIpInput.$refs.input.focus();
        //   this.$forceUpdate()
        // });
      },
      changeSearch(value, props) {
        // this.$forceUpdate();
        props.row.ips = this.iplistDataBak[props.$index].ips.filter(data => {
          //如果input有值就判断返回
          if (value) {
            if ((data.hasOwnProperty('arp') && data.arp.mac.toLowerCase().includes(value.toLowerCase()))
              || (data.hasOwnProperty('oldarp') && data.oldarp.mac.toLowerCase().includes(value.toLowerCase()))) return true
            else return false
          } else {
            //没有值就是全部行返回
            return true
          }
        })
      },
      changeSearchName(value, props) {
        // this.$forceUpdate();
        props.row.ips = this.iplistDataBak[props.$index].ips.filter(data => {
          //如果input有值就判断返回
          if (value) {
            if (data.hasOwnProperty('name') && data.name.includes(value))
              return true
            else return false
          } else {
            //没有值就是全部行返回
            return true
          }
        })
      },
      //真正提交siwch切换状态
      async changeTimeSan(row) {
        var snmpInfo = JSON.parse(JSON.stringify(row.snmpInfo))
        snmpInfo.timeSan = !row.snmpInfo.timeSan
        let action = snmpInfo.timeSan ? 'start/' : 'stop/'
        try {
          const res = await this.$axios.put('/api/task/' + action + row._id, {'snmpInfo': snmpInfo})
          if (res.status === 200 && res.data.code === "success") {
            this.$message.success("提交成功")
            row.snmpInfo.timeSan = !row.snmpInfo.timeSan
          } else {
            this.$message.error('提交失败')
            console.log(e)
          }
        } catch (e) {
          this.$message.error('提交失败')
          console.log(e)
        }
      },
      //先询问
      changeTimeSanFirst(row) {
        let flag = row.snmpInfo.timeSan //保存点击之后v-modeld的值(true，false)
        row.snmpInfo.timeSan = !row.snmpInfo.timeSan//保持switch点击前的状态
      },
    },
  }
</script>

<style lang="less">
  .label {
    font-weight: bold;
    width: 120px;
    margin-right: 20px;
    text-align: right;
    display: inline-block;
    align-self: center;
    flex-shrink: 0;
  }

  #queryAreaSelect {
    /deep/ .el-select-dropdown__item.selected {
      color: white;
    }
  }

  .areaSelect {
    margin-right: 20px;

    .el-select-dropdown__item.selected {
      color: white;
    }

  }


  .yanseSelect {
    color: white;

    /deep/ .el-select-dropdown__item.selected {
      color: white;
    }
  }

  .titlelabel {
    margin-left: 20px;

    font-weight: bolder;
  }

  .row-bg {
    background: #E9EEF3;
    padding: 20px;
  }

  /deep/ .el-table .el-table__expanded-cell {
    padding: 0px 2px;
  }

  .listdiv {
    width: fit-content;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-items: center;

  }

  .pagination {
    background: white;
  }

  .el-drawer__container {
    overflow: auto;
  }
</style>
